import datetime
import os

from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class foreign_body:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'foreign_body_record')
        self.cf = change_format()
        self.sm = sqlMontage()

    def get_foreign_body_list(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = f"select fbr.*,oi.`overhaul_code`,oi.`overhaul_name`,oi.`overhaul_addr`,oc.`overhaul_config_name`,ci.`camera_code`,ci.`camera_name`,ci.`camera_addr`,ci.`width`,ci.`height` from `foreign_body_record` fbr join `overhaul_info` oi on fbr.`overhaul_info_id`=oi.`overhaul_info_id` and oi.`del_flag`='{self.st.get_status('delFlag', '存在')}' join `overhaul_config` oc on fbr.`overhaul_info_id`=oc.`overhaul_info_id` and oc.`del_flag`='{self.st.get_status('delFlag', '存在')}' join `camera_info` ci on oc.`overhaul_config_id`=ci.`overhaul_config_id` and ci.`del_flag`='{self.st.get_status('delFlag', '存在')}' and fbr.`camera_info_id`=ci.`camera_info_id` where oi.`status`='{self.st.get_status('status', '启用')}' "
        sql = ""
        pages = ''
        if data != {}:
            if data.get('pageNum') is not None and data.get('pageSize') is not None:
                if data['pageNum'] != '' and data['pageSize'] != '':
                    pages = " limit {},{}".format(int(data['pageNum']) * int(data['pageSize']) - int(data['pageSize']),
                                                  int(data['pageSize']))
            if data.get('overhaulInfoId') is not None:
                if data['overhaulInfoId'] != '':
                    sql = sql + " and oi.`overhaul_info_id`={}".format(data['overhaulInfoId'])
            if data.get('overhaulConfigId') is not None:
                if data['overhaulConfigId'] != '':
                    sql = sql + " and oc.`overhaul_config_id`={}".format(data['overhaulConfigId'])
            if data.get('cameraInfoId') is not None:
                if data['cameraInfoId'] != '':
                    sql = sql + " and ci.`camera_info_id`={}".format(data['cameraInfoId'])
            if data.get('status') is not None:
                if data['status'] != '':
                    sql = sql + " and fbr.`status`={}".format(data['status'])
            if data.get('beginTime') is not None and data.get('endTime') is not None:
                if data['beginTime'] != '' and data['endTime'] != '':
                    sql = (sql + " and ('{}'<=fbr.`create_time` and fbr.`create_time`<='{}')".
                           format(data['beginTime'], data['endTime']))
        total = self.db.gets(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY fbr.`create_time` DESC ' + f'{pages}'
        else:
            sql = sqls + ' ORDER BY fbr.`create_time` DESC ' + f'{pages}'
        res = self.db.gets(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                r['url'] = 'http://' + r['camera_addr'] + ':8888/api/foreign/body/' + r['addr']
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    def get_foreign_body_disposal_record(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = f"select fbr.*,su.`nick_name`,su.`phone_number`,dr.`disposal_record_id`,dr.`status` as `disposal_status`,dr.`create_by`,dr.`create_time` as disposal_create_time,dr.`remark` from `foreign_body_record` fbr join `disposal_record` dr on fbr.`foreign_body_id`=dr.`foreign_body_id` join `sys_user` su on dr.`create_by`=su.`user_name` and su.`del_flag`='{self.st.get_status('delFlag', '存在')}' and su.`status`='{self.st.get_status('status', '启用')}' where 1=1 "
        sql = ""
        pages = ''
        if data != {}:
            if data.get('pageNum') is not None and data.get('pageSize') is not None:
                if data['pageNum'] != '' and data['pageSize'] != '':
                    pages = " limit {},{}".format(int(data['pageNum']) * int(data['pageSize']) - int(data['pageSize']),
                                                  int(data['pageSize']))
            if data.get('foreignBodyId') is not None:
                if data['foreignBodyId'] != '':
                    sql = sql + " and fbr.`foreign_body_id`={}".format(data['foreignBodyId'])
            if data.get('beginTime') is not None and data.get('endTime') is not None:
                if data['beginTime'] != '' and data['endTime'] != '':
                    sql = (sql + " and ('{}'<=fbr.`create_time` and fbr.`create_time`<='{}')".
                           format(data['beginTime'], data['endTime']))
        total = self.db.gets(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY dr.`create_time` DESC ' + f'{pages}'
        else:
            sql = sqls + ' ORDER BY dr.`create_time` DESC ' + f'{pages}'
        res = self.db.gets(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    # 异物记录处置
    def edit_foreign_body(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 修改状态
        if 'createTime' in data:
            del data['createTime']
        data['update_by'] = userInfo['userName']
        data['update_time'] = times
        edit_sql = self.sm.edit_sql_data(data, 'foreign_body_record', 'foreign_body_id', data['foreignBodyId'])
        self.db.edits(edit_sql, 'foreign_body_record')
        # 新增记录
        data['create_by'] = userInfo['userName']
        data['create_time'] = times
        add_sql = self.sm.add_sql_data(data, 'disposal_record')
        self.db.adds(add_sql, 'disposal_record')
        return result
